package com.qdum.glory.datasearch.dao.es;
import com.qdum.glory.datasearch.dao.es.trace.EsClientInvocationHandler;
import com.qdum.glory.datasearch.dao.es.trace.EsClientPreferenceComponent;
import com.qdum.glory.datasearch.dao.es.trace.EsClientTraceInvokeComponent;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.Header;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
import org.elasticsearch.client.Node;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Arrays;
import java.util.Objects;

import static org.slf4j.LoggerFactory.*;

/**
 * Elasticsearch 配置
 * @author liuf
 * @time 2020-08-27
 */
@Configuration
public class ElasticsearchRestHighLevelClientConfiguration {

    private static final Logger logger = getLogger(ElasticsearchRestHighLevelClientConfiguration.class);
    @Autowired
    private ElasticsearchConf elasticsearchConf;
    private static final int ADDRESS_LENGTH = 2;
    private static final String HTTP_SCHEME = "http";
    @Autowired
    RestClientBuilder restClientBuilder;
    @Bean
    public HttpHost[] getHttpHost(){
        HttpHost[] hosts = Arrays.stream(elasticsearchConf.getClusterNodes())
                .map(this::makeHttpHost)
                .filter(Objects::nonNull)
                .toArray(HttpHost[]::new);
        return hosts;
    }

    private HttpHost makeHttpHost(String s) {
        assert StringUtils.isNotEmpty(s);
        String[] address = s.split(":");
        if (address.length == ADDRESS_LENGTH) {
            String ip = address[0];
            int port = Integer.parseInt(address[1]);
            return new HttpHost(ip, port, HTTP_SCHEME);
        } else {
            return null;
        }
    }

    @Bean
    public RestHighLevelClient restHighLevelClient(){
        if (StringUtils.isNotBlank(elasticsearchConf.getUsername()) && StringUtils.isNotBlank(elasticsearchConf.getPassword())) {
            final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(elasticsearchConf.getUsername(), elasticsearchConf.getPassword()));
            //1.Authorization 验证方式 Header[] defaultHeaders = new Header[]{new BasicHeader("Authorization", "Bearer u6iuAxZ0RG1Kcm5jVFI4eU4tZU9aVFEwT2F3")};
            restClientBuilder = RestClient.builder(getHttpHost())
                    //.setDefaultHeaders(defaultHeaders) 1。Authorization 验证方式设置
                    .setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
                        @Override
                        public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
                            httpClientBuilder.setMaxConnTotal(elasticsearchConf.getProperties().maxConnectTotal);
                            httpClientBuilder.setMaxConnPerRoute(elasticsearchConf.getProperties().maxConnectPerRoute);
                            httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
                            return httpClientBuilder;
                        }
                    })
                    .setRequestConfigCallback(new RestClientBuilder.RequestConfigCallback() {
                        @Override
                        public RequestConfig.Builder customizeRequestConfig(
                                RequestConfig.Builder requestConfigBuilder) {
                            return requestConfigBuilder
                                    .setConnectTimeout(elasticsearchConf.getProperties().connectTimeOut)
                                    .setSocketTimeout(elasticsearchConf.getProperties().socketTimeOut)
                                    .setConnectionRequestTimeout(elasticsearchConf.getProperties().connectionRequestTimeOut);
                        }
                    });
        } else {
            ///新数据源访问地址
            restClientBuilder = RestClient.builder(getHttpHost())
                    .setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
                        @Override
                        public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
                            httpClientBuilder.setMaxConnTotal(elasticsearchConf.getProperties().maxConnectTotal);
                            httpClientBuilder.setMaxConnPerRoute(elasticsearchConf.getProperties().maxConnectPerRoute);
                            return httpClientBuilder;
                        }
                    })
                    .setRequestConfigCallback(new RestClientBuilder.RequestConfigCallback() {
                        @Override
                        public RequestConfig.Builder customizeRequestConfig(
                                RequestConfig.Builder requestConfigBuilder) {
                            return requestConfigBuilder
                                    .setConnectTimeout(elasticsearchConf.getProperties().connectTimeOut)
                                    .setSocketTimeout(elasticsearchConf.getProperties().socketTimeOut)
                                    .setConnectionRequestTimeout(elasticsearchConf.getProperties().connectionRequestTimeOut);
                        }
                    }).setFailureListener(new RestClient.FailureListener() {
                        @Override
                        public void onFailure(Node node) {
                            super.onFailure(node);
                            logger.error("elasticsearch 节点异常 请联系运维人员查看 集群是否异常。");
                        }});
        }
        return new RestHighLevelClient(restClientBuilder);
    }

    /**
     * 关闭连接
     */
    @Bean
    public void close() {
        if (restClientBuilder != null) {
            try {
                restClientBuilder.build().close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}
